<template>
  <view class="baseForm">
    <u-loading-page :loading="loading"></u-loading-page>
    <view v-if="!loading" class="overhidden">
      <view class="detail card">
        <view class="flex flex-col justify-between flex-1 h-full">
          <view class="record-content">
            <view
              class="flex title justify-between"
              @click="() => (isCollapse = !isCollapse)"
              :class="!isCollapse ? 'u-m-b-24' : 'u-m-b-10'"
            >
              <text>基本信息</text>
              <u-icon
                v-show="!isCollapse"
                name="arrow-up"
                color="#000a7b"
              ></u-icon>
              <u-icon
                v-show="isCollapse"
                name="arrow-down"
                color="#000a7b"
              ></u-icon>
            </view>
            <view v-show="!isCollapse">
              <view class="record-item">
                <text>维护编号</text>
                <text>{{ taskInfo?.taskNo || "" }}</text>
              </view>
             <!-- <view class="record-item">
                <text>维护名称</text>
                <text>{{ taskInfo?.taskName || "" }}</text>
              </view> -->
              <view class="record-item">
                <text>维护状态</text>
                <view
                  v-if="taskInfo?.taskStatus === 0"
                  class="flex align-center"
                >
                  <u-icon color="#000a7b" name="pause-circle"></u-icon>
                  待维护
                </view>
                <view
                  v-if="taskInfo?.taskStatus === 1"
                  class="flex align-center"
                >
                  <u-icon color="#000a7b" name="play-circle-fill"></u-icon>
                  维护中...
                </view>
                <view
                  v-if="taskInfo?.taskStatus === 2"
                  class="flex align-center"
                >
                  <u-icon color="#000a7b" name="checkmark-circle"></u-icon>
                  已完成
                </view>
              </view>
              <view class="record-item">
                <text>计划执行时间</text>
                <text>
                  {{ taskInfo?.planExecuteTime || "" }}
                </text>
              </view>
              <view
                class="record-item"
                v-if="taskInfo?.assetPhotos && taskInfo?.assetPhotos.length"
              >
                <text>图片/文档</text>
                <text style="text-decoration: underline" @click="previewImage">
                  查看
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- <view class="plan card record-content">
				<view class="title">计划中的高风险活动</view>
				<view class="">{{ taskInfo?.taskTypeNameList }}</view>
			</view> -->
      <view class="plan card record-content pb-10">
        <view class="title flex justify-between">
          <text>维护详情</text>
        </view>
        <view class="flex justify-between" style="margin-bottom: 7px">
          <view @click="showPositionPicker" class="flex input-box">
            <u--input
              v-model="position"
              border="none"
              placeholder="请选择位置"
              readonly
              class="input-self"
            ></u--input>
            <image
              @click.stop="clearInfo()"
              v-show="position"
              src="@/static/image/delete.png"
            />
          </view>
          <u-button
            type="primary"
            icon="search"
            class="search-btn"
            @click="resetPageList"
          ></u-button>
        </view>
        <u-subsection
          :list="list"
          :current="currentSub"
          @change="sectionChange"
          :fontSize="14"
          class="u-m-b-14"
        ></u-subsection>
        <!-- 列表 -->
        <u-list
          ref="tableScroll"
          @scrolltolower="scrolltolower"
          class="list"
          v-if="total"
          height="auto"
          lowerThreshold="50px"
          :pagingEnabled="true"
          :scrollable="false"
        >
          <u-list-item
            v-for="(item, index) in tableList"
            :key="item.id"
            @click="
              jump(
                '/eam/mold/maintainPlan/check',
                item.id,
                item?.orderStatus >= 2 ? 1 : 0
              )
            "
          >
            <view>
              <view class="flex flex-row justify-between flex-1 h-full">
                <view class="record-content history">
                  <view class="record-item">
                    <text>{{ item?.assetCode || "" }}</text>
                    <!-- <text>{{ item?.createTime }}</text> -->
                    <view
                      v-if="item?.orderStatus == 0"
                      class="flex align-center"
                    >
                      待维护
                    </view>
                    <view
                      v-if="item?.orderStatus == 1"
                      class="flex align-center"
                    >
                      维护中
                    </view>
                    <view
                      v-if="item?.orderStatus == 2"
                      class="flex align-center"
                    >
						完成
                      <!-- <text v-if="item?.checkResult == 1"> 正常 </text>
                      <text v-if="item?.checkResult == 0"> 异常 </text> -->
                    </view>
                  </view>
                  <view class="record-item">
                    <text>{{ item?.assetName || "" }}</text>
                    <text>
                      {{ item?.locationName || "" }}
                    </text>
                  </view>

                  <!-- <view class="record-item">
										<text>作业状态</text>
										<view v-if="item?.dangerTaskStage == 1" class="flex align-center">作业前</view>
										<view v-if="item?.dangerTaskStage == 2" class="flex align-center">作业中...</view>
										<view v-if="item?.dangerTaskStage == 3" class="flex align-center">作业后</view>
									</view> -->
                  <view class="record-item align-center">
                    <view class="flex">
                      <u-text
                        v-if="item?.notInspectedNumber != null"
                        :text="`未维护(${item?.notInspectedNumber || 0})`"
                        :size="14"
                        style="
                          display: inline;
                          flex: none;
                          width: auto;
                          margin-right: 5px;
                        "
                      ></u-text>
                      <!-- <u-text
                        v-if="item?.exceptionNumber"
                        type="error"
                        :text="`异常(${item?.exceptionNumber})`"
                        :size="14"
                        style="display: inline; flex: none; width: auto"
                      ></u-text> -->
                    </view>

                    <text class="font-14">
                      {{ getSecondTime(item?.workTime) || "" }}
                    </text>
                  </view>
                  <!-- <view class="record-item">
										<text>检查人</text>
										<text>{{ item?.createdUserName }}</text>
									</view> -->
                </view>
                <view
                  class="flex jump align-center justify-right"
                  style="width: 20px"
                >
                  <u-icon name="arrow-right" color="#16254e" size="14"></u-icon>
                </view>
              </view>
              <u-divider v-if="index != tableList.length - 1"></u-divider>
            </view>
          </u-list-item>
          <view class="flex justify-center" v-show="tableLoading">
            <u-loading-icon color="#000a7b"></u-loading-icon>
          </view>
        </u-list>
        <!-- 空数据 -->
        <view v-else>
          <u-empty
            mode="list"
            icon="http://cdn.uviewui.com/uview/empty/list.png"
          ></u-empty>
        </view>
      </view>
    </view>
    <u-album :urls="assetPhotos" ref="uAlbumRef" v-show="showIamge"></u-album>
    <!-- 树形选择器 -->
    <ba-tree-picker
      ref="positionPicker"
      :multiple="false"
      @select-change="positionChange"
      title="位置"
      :selectedData="showPositionValue"
      :localdata="positionList"
      valueKey="id"
      textKey="locationName"
      childrenKey="nodes"
    />
  </view>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { onShow, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
import { http } from "@/utils/http";
import { PageResult } from "@/types/type";
import { getSecondTime } from "@/utils/common";
import BaTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue";
const props = defineProps({
  id: {
    type: String,
    default: "",
  },
});

// 是否折叠
const isCollapse = ref(true);

// 预览url前缀
const uploadApi = process.env.VITE_APP_UPLOAD_API;
const upPreviewUrl = `${uploadApi}/system/fileCenter/preview/`;

const taskInfo = ref();
const assetPhotos = ref([]);
const showIamge = ref(false);
const uAlbumRef = ref();
const loading = ref(false);
async function initPage() {
  try {
    loading.value = true;
    const result: any = await http({
      method: "GET",
      url: `/eam/mouldMaintainTask/getView/${props.id}`,
      data: {},
    }).finally(() => {
      loading.value = false;
      uni.stopPullDownRefresh();
    });
    taskInfo.value = result.data;

    // 获取预览图片
    const list = [];
    taskInfo.value.assetPhotos?.map((e) => {
      list.push(`${upPreviewUrl}${e.url}`);
    });
    assetPhotos.value = list;
  } catch (e) {
    console.log(e);
  }
}

function previewImage() {
  uAlbumRef.value.onPreviewTap();
}

const currentSub = ref(0);
const list = ref(["未维护", "已维护"]);
function sectionChange(index) {
  currentSub.value = index;
  resetPageList();
}
// @change="sectionChange"
// 显示选择器
const positionId = ref("");
const position = ref("");
const positionPicker = ref();
function showPositionPicker() {
  positionPicker.value._show();
}
//监听选择（ids为数组）
const showPositionValue = ref([]);
function positionChange(ids, names) {
  console.log("ids", ids);
  positionId.value = ids[0] ?? "";
  position.value = names ?? "";
  showPositionValue.value = ids[0] ? [ids[0]] : [];
}

// 清空数据
function clearInfo() {
  positionId.value = "";
  position.value = "";
  if (positionPicker.value?._reTreeList) {
    positionPicker.value._reTreeList();
  }
}
// 获取位置列表
const positionList = ref();
async function getPositionList() {
  const { data } = await http({
    method: "POST",
    url: `/eam/locationInfo/getTree`,
    data: {},
  });
  positionList.value = data;
}

// 列表定义
const tableList = ref([]);
const tableLoading = ref(false);
const current = ref(0);
const totalPage = ref(0);
const total = ref(0);

const locationId = ref("");
async function loadmore(type?: string) {
  try {
    current.value += 1;
    tableLoading.value = true;
    const result: PageResult<any> = await http({
      method: "POST",
      url: "/eam/mouldMaintainOrder/queryByTask",
      data: {
        current: current.value,
        size: 20,
        data: {
          inspectionTaskId: props.id,
          locationId: positionId.value,
          inspectionStatus:
            currentSub.value === 1 ? 2 : currentSub.value === 2 ? 3 : 0,
        },
      },
    }).finally(() => {
      tableLoading.value = false;
    });
    const list = result.data;
    for (let i = 0; i < list.length; i++) {
      tableList.value.push(list[i]);
    }
    totalPage.value = result.page;
    total.value = result.total;
    type === "refresh" && uni.stopPullDownRefresh();
  } catch (e) {
    console.log(e);
  }
}

// 网页跳转
function jump(item, id, isRead) {
  uni.navigateTo({
    url: `/pages${item}?id=${id}&isRead=${isRead}`,
  });
}

onReachBottom(() => {
  scrolltolower();
});

const scrolltolower = () => {
  totalPage.value > current.value && loadmore();
};

function resetPageList() {
  tableList.value = [];
  current.value = 0;
  loadmore("refresh");
}

onPullDownRefresh(() => {
  initPage();
  resetPageList();
});

onShow(() => {
  tableList.value = [];
  current.value = 0;
  props.id && initPage();
  props.id && loadmore();
  getPositionList();
});
</script>

<style lang="scss" scoped>
$primary-color: #16254e;
.flex-row {
  flex-direction: row;
}
.justify-right {
  justify-content: flex-end;
}
.history {
  width: calc(100% - 20px);
  .record-item {
    margin: 5px 0;
  }
}
.card {
  background-color: #fff;
  margin: 5px 10px;
  border-radius: 8px;
  padding: 12px 12px;
  transition: all 300ms ease;
}

uni-page-body {
  height: 100%;
  background-color: #f9f9fc;
}

.baseForm {
  background-color: #f9f9fc;
  display: block;
}

.title {
  font-size: 16px;
  margin: 4px 0 10px;
  font-weight: bold;
}

.u-divider {
  margin: 5px 0;
}

.pb-10 {
  padding-bottom: 10px;
}
.input-box {
  // width: calc(100% - 56px);
  width: 100%;
  border: 0.5px solid #dadbde !important;
  border-radius: 4px;
  height: 32px;
  line-height: 32px;
  .u-input {
    pointer-events: none;
    height: 32px;
    line-height: 32px;
    padding-left: 10px !important;
  }
  image {
    padding: 6px 6px;
    width: 20px;
    height: 20px;
  }
}

.search-btn {
  width: 40px;
  height: 34px;
  margin-left: 6px;
  border-radius: 4px;
}
:deep(.u-empty__text) {
  margin-bottom: 30px;
}
</style>
